﻿using System;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

namespace NazTek.Documenter.Ssis.Control.Tasks.PipeSubComponent
{
    internal sealed class ConditionalSplit : Base
    {
        internal ConditionalSplit(IDTSComponentMetaData100 subComponent)
            : base(subComponent, null)
        {
        }

        protected override Operation GetOperation(SsisPipe parent)
        {
            var statement = new StringBuilder("Inputs:<br>");
            foreach (var inp in Metadata.InputCollection[0].InputColumnCollection.Cast<IDTSInputColumn100>().ToArray())
                statement.AppendFormat("\t{0}<br>", inp.Name);
            statement.AppendLine("<br>Output Splits:<table style=\"font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #565051\"><tr>");

            var allOutputs = Metadata.OutputCollection.Cast<IDTSOutput100>().ToArray();
            Func<IDTSOutput100, IDTSCustomProperty100> getOutProp = o => o.CustomPropertyCollection
                .Cast<IDTSCustomProperty100>().FirstOrDefault(pn => pn.Name == "FriendlyExpression");
            var outDic = allOutputs.Where(o => getOutProp(o) != null)
                    .ToDictionary<IDTSOutput100, string, string>(output => output.Name, output => getOutProp(output).Value);
            foreach (var o in outDic.Keys)
                statement.AppendFormat("<td style=\"vertical-align: top; border: 1px solid #98AFC7; background-color: #DBE5F0\">{0}</td>", o);
            statement.AppendLine("</tr><tr>");
            foreach (var o in outDic.Values)
                statement.AppendFormat("<td style=\"vertical-align: top; border: 1px solid #98AFC7\">{0}</td>", o);
            statement.AppendLine("</tr></table>");

            return new Operation
            {
                ConnectionName = "Not Applicable",
                Statement = statement.ToString()
            };
        }
    }
}